using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
using WebApplication1.Data;
using Microsoft.EntityFrameworkCore;

namespace WebApplication1.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class UserController : ControllerBase
    {
        private readonly BookDbContext _context;

        public UserController(BookDbContext context)
        {
            _context = context;
        }
        /// <summary>
        /// 创建用户
        /// </summary>
        /// <param name="user">用户信息</param>
        /// <returns>返回结果</returns>
        [HttpPost]
        public async Task<Result<User>> Create(User user)
        {
            try
            {
                // 对密码进行加密
                user.Password = Utils.PasswordHelper.EncryptPassword(user.Password);
                _context.Users.Add(user);
                await _context.SaveChangesAsync();
                return Result<User>.Ok(user, "用户创建成功");
            }
            catch (Exception ex)
            {
                return Result<User>.Error($"用户创建失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 更新用户信息
        /// </summary>
        /// <param name="user">用户信息</param>
        /// <returns>返回结果</returns>
        [HttpPut]
        public async Task<Result<User>> Update(User user)
        {
            try
            {
                var existingUser = await _context.Users.FindAsync(user.Id);
                if (existingUser == null)
                {
                    return Result<User>.Error("用户不存在");
                }

                // 如果提供了新密码，需要进行加密
                if (!string.IsNullOrEmpty(user.Password))
                {
                    user.Password = Utils.PasswordHelper.EncryptPassword(user.Password);
                }

                _context.Entry(existingUser).CurrentValues.SetValues(user);
                await _context.SaveChangesAsync();
                return Result<User>.Ok(user, "用户信息更新成功");
            }
            catch (Exception ex)
            {
                return Result<User>.Error($"用户信息更新失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns>返回结果</returns>
        [HttpDelete("{id}")]
        public async Task<Result<bool>> Delete(int id)
        {
            try
            {
                var user = await _context.Users.FindAsync(id);
                if (user == null)
                {
                    return Result<bool>.Error("用户不存在");
                }

                _context.Users.Remove(user);
                await _context.SaveChangesAsync();
                return Result<bool>.Ok(true, "用户删除成功");
            }
            catch (Exception ex)
            {
                return Result<bool>.Error($"用户删除失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns>返回结果</returns>
        [HttpGet("{id}")]
        public async Task<Result<User>> Get(int id)
        {
            try
            {
                var user = await _context.Users.FindAsync(id);
                if (user == null)
                {
                    return Result<User>.Error("用户不存在");
                }
                return Result<User>.Ok(user, "获取用户信息成功");
            }
            catch (Exception ex)
            {
                return Result<User>.Error($"获取用户信息失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 获取所有用户信息
        /// </summary>
        /// <returns>返回所有用户信息列表</returns>
        [HttpGet]
        public async Task<Result<List<User>>> GetAll()
        {
            try
            {
                var users = await _context.Users.ToListAsync();
                return Result<List<User>>.Ok(users, "获取所有用户信息成功");
            }
            catch (Exception ex)
            {
                return Result<List<User>>.Error($"获取用户列表失败：{ex.Message}");
            }
        }
        /// <summary>
        /// 用户登录验证
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        /// <returns>返回登录结果和JWT令牌</returns>
        [HttpPost("login")]
        public async Task<Result<string>> Login([FromBody] LoginModel model)
        {
            try
            {
                var user = await _context.Users
                    .FirstOrDefaultAsync(u => u.Username == model.Username);

                if (user == null)
                {
                    return Result<string>.Error("用户名或密码错误");
                }

                var encryptedPassword = Utils.PasswordHelper.EncryptPassword(model.Password);
                if (user.Password != encryptedPassword)
                {
                    return Result<string>.Error("用户名或密码错误");
                }

                // 更新最后登录时间
                user.LastLoginTime = DateTime.Now;
                await _context.SaveChangesAsync();

                // 生成JWT令牌
                var token = Utils.JwtHelper.GenerateToken(user);
                return Result<string>.Ok(token, "登录成功");
            }
            catch (Exception ex)
            {
                return Result<string>.Error($"登录失败：{ex.Message}");
            }
        }
        /// <summary>
        /// 修改用户密码
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <param name="oldPassword">旧密码</param>
        /// <param name="newPassword">新密码</param>
        /// <param name="confirmPassword">确认新密码</param>
        /// <returns>返回结果</returns>
        [HttpPost("changePassword")]
        public async Task<Result<bool>> ChangePassword([FromForm] int id, [FromForm] string oldPassword, [FromForm] string newPassword, [FromForm] string confirmPassword)
        {
            try
            {
                var user = await _context.Users.FindAsync(id);
                if (user == null)
                {
                    return Result<bool>.Error("用户不存在");
                }

                // 验证旧密码
                if (!Utils.PasswordHelper.VerifyPassword(oldPassword, user.Password))
                {
                    return Result<bool>.Error("旧密码错误");
                }

                // 验证两次输入的新密码是否一致
                if (newPassword != confirmPassword)
                {
                    return Result<bool>.Error("两次输入的新密码不一致");
                }

                // 更新密码
                user.Password = Utils.PasswordHelper.EncryptPassword(newPassword);
                await _context.SaveChangesAsync();

                return Result<bool>.Ok(true, "密码修改成功");
            }
            catch (Exception ex)
            {
                return Result<bool>.Error($"密码修改失败：{ex.Message}");
            }
        }
    }
}